<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>分销设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="分销开关" props="subCommissionEnable">
      <el-switch
        v-model="formData.subCommissionEnable"
        @change="changeSubCommissionEnable"
      ></el-switch>
    </el-form-item>
    <el-form-item label="分销类型" props="subCommissionType" v-if="formData.subCommissionEnable">
      <el-radio-group
        v-model="formData.subCommissionType"
        class="w-80"
        @change="changeSubCommissionType"
      >
        <el-radio :value="false">默认设置</el-radio>
        <el-radio :value="true" class="radio">单独设置</el-radio>
      </el-radio-group>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>销量设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品在线下渠道有销售，可以填写该商品在线下渠道的销售数据。线上展示销量数据为线下销量+线上销量之和。
      </span>
    </div>
    <el-form-item label="线下销量" prop="virtualSalesCount">
      <el-input-number
        v-model="formData.virtualSalesCount"
        @change="virtualSalesCountChange"
        :min="0"
        placeholder="请输入线下销量"
        class="w-80!"
      />
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>商品规格 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="规格类型" props="specType">
      <el-radio-group v-model="formData.specType" class="w-80" @change="onChangeSpec">
        <el-radio :value="false" class="radio">单规格</el-radio>
        <el-radio :value="true">多规格</el-radio>
      </el-radio-group>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>规格属性</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> 不同规格商品的图片、零售价、成本价等不同的参数的设置 </span>
    </div>
    <!-- 多规格添加-->
    <el-form-item v-if="!formData.specType">
      <SkuList
        ref="skuListRef"
        :prop-form-data="formData"
        :property-list="propertyList"
        :rule-config="ruleConfig"
      />
    </el-form-item>
    <el-form-item v-if="formData.specType" label="商品规格">
      <ProductAttributes
        :is-detail="isDetail"
        :prop-form-data="formData"
        :property-list="propertyList"
        @success="generateSkus"
      />
      <el-button class="mb-10px mr-15px" @click="handleAttributesAdd">添新加规格</el-button>
    </el-form-item>
    <template v-if="formData.specType && propertyList.length > 0">
      <el-form-item v-if="!isDetail" label="批量设置">
        <SkuList :is-batch="true" :prop-form-data="formData" :property-list="propertyList" />
      </el-form-item>
      <el-form-item label="规格列表">
        <SkuList
          ref="skuListRef"
          :is-detail="isDetail"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
        />
      </el-form-item>
    </template>
  </el-form>
  <!-- 商品属性添加 Form 表单 -->
  <ProductPropertyAddForm ref="attributesAddFormRef" :propertyList="propertyList" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget, generateNumericUUID, generateSortNumericUUID } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig,
  SkuList,
  fromDataRule
} from '@/views/mall/product/spu/components/index'
import ProductAttributes from './ProductAttributes.vue'
import ProductPropertyAddForm from './ProductPropertyAddForm.vue'
import type { Spu } from '@/api/mall/product/spu'
defineOptions({ name: 'ProductSpuSkuForm' })

// sku 相关属性校验规则
const ruleConfig: RuleConfig[] = [
  // {
  //   name: 'price',
  //   rule: (arg) => arg >= 0.0,
  //   message: '商品零售价格必须大于等于 0.00 元！！！'
  // }
]

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const attributesAddFormRef = ref() // 添加商品属性表单
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListRef = ref() // 商品属性列表 Ref
const formData = reactive<Spu>({
  specType: false, // 商品规格
  spuType: 1, //商品类型
  skus: [],
  salesChannel: [],
  subCommissionType: false, // 分销类型
  subCommissionEnable: false, //分销开关
  virtualSalesCount: 0
})
/**虚拟销量 */
const virtualSalesCountChange = () => {
  Object.assign(props.propFormData, formData)
}
/** 分销类型 */

const changeSubCommissionEnable = () => {
  formData.subCommissionType = false
  Object.assign(props.propFormData, formData)
}
const changeSubCommissionType = () => {
  // 默认为零，类型切换后也要重置为零
  for (const item of formData.skus!) {
    item.firstBrokeragePrice = 0
    item.secondBrokeragePrice = 0
  }
  Object.assign(props.propFormData, formData)
}
const rules = reactive({
  specType: [required],
  subCommissionType: [required]
})
const handleAttributesAdd = () => {
  let data = {
    id: generateSortNumericUUID(),
    name: '',
    values: []
  }
  propertyList.value.push(data)
}
onMounted(() => {})
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)
// watch(
//   () => formData,
//   () => {
//     Object.assign(props.propFormData, formData)
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    skuListRef.value?.validateSku()
    await unref(formRef).validate()

    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    // message.error('【商品规格】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 选择规格 */
const onChangeSpec = () => {
  // 重置商品属性列表
  propertyList.value = []
  // 重置sku列表
  formData.skus = [
    {
      price: 0, // 商品价格 零售价
      marketPrice: 0, // 市场价
      costPrice: 0, // 成本价
      barCode: '', // 商品条码
      picUrl: '', // 图片地址
      stock: 0, // 库存
      weight: 0, // 商品重量
      volume: 0, // 商品体积
      skuType: undefined, //商品属性
      usableTimes: 0, //可用次数
      merchantCode: '', //商家编码
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0, // 二级分销的佣金
      firstBrokeragePercent: 0, // 一级分销的佣金 比例
      secondBrokeragePercent: 0, // 二级分销的佣金 比例
      firstBrokerageType: 2, // 一级分销的佣金类型
      secondBrokerageType: 2, // 二级分销的佣金类型
      unit: '', //商品单位,
      skuId: generateNumericUUID() //前端自定义生成的skuId
    }
  ]
  // 重置商品权限
  Object.assign(formData, fromDataRule)
  Object.assign(props.propFormData, formData)
}

/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
  skuListRef.value.generateTableData(propertyList)
  Object.assign(props.propFormData, formData)
}
</script>
